package com.ljm.controller;

import com.ljm.service.LoginService;
import com.ljm.service.LoginServiceImpl;
import com.ljm.util.StausCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("*.user")
public class LoginServlet extends HttpServlet {

    public LoginServlet() {
        super();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("GBK");
        //接受页面传递的数据
        //但凡页面传递的数据都是String类型
        //String--》Unicode字符集--》万国码--》凡是键盘上敲出来的都属于Unicode字符集
        //char--》Unicode--》2字节--》无符号位--》不会超过66535
        String url=req.getServletPath();
        if(url.equals("/login.user")) {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        //LoginService ls=new LoginServiceImpl();
            // 调用service 层
            LoginService ls = new LoginServiceImpl();
            int result = ls.validateUserAndPwd(username,password);
            if(result == StausCode.USERNAME_ERROR){
                //用户名不存在，转发回到登录页
                req.setAttribute("msg","用户名不存在！");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            } else if (result == StausCode.SUCCESS) {
                //2 验证通过
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            } else if (result == StausCode.PASSWORD_ERROR) {
                //用户名正确 密码错误
                req.setAttribute("msg","密码错误！");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }else{
                req.setAttribute("msg","未知错误！");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
